package cn.tedu.learn.tea.infrastructure;

import cn.tedu.learn.tea.dao.ContentDao;
import cn.tedu.learn.tea.domain.bo.ContentBO;
import cn.tedu.learn.tea.domain.bo.ContentListBO;
import cn.tedu.learn.tea.domain.repository.ContentRepository;
import cn.tedu.learn.tea.infrastructure.data.converter.ContentConverter;
import cn.tedu.learn.tea.po.Content;
import cn.tedu.learn.tea.protocol.parm.ContentParam;
import cn.tedu.learn.tea.protocol.parm.ContentUpdateParam;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 内容Repository实现类
 */
@Repository
public class ContentRepositoryImpl implements ContentRepository {

    @Autowired
    private ContentDao contentDao;

    @Autowired
    private ContentConverter contentConverter;

    @Override
    public Integer insert(ContentParam contentParam) {
        Content content = contentConverter.paramToPo(contentParam);
        contentDao.insert(content);
        return content.getId();
    }

    @Override
    public Integer update(ContentUpdateParam contentUpdateParam) {
        Content content = contentConverter.paramToPo(contentUpdateParam);
        return contentDao.update(content);
    }

    @Override
    public Integer delete(Integer contentId) {
        return contentDao.delete(contentId);
    }

    @Override
    public PageInfo<ContentListBO> list(Integer page, Integer pageSize) {
        //1.开启分页查询
        Page<Object> p = PageHelper.startPage(page, pageSize);

        //2.查询数据
        List<Content> contentList = contentDao.list();

        //3.转换BO对象
        List<ContentListBO> contentBoList = contentConverter.poListToBoList(contentList);

        //4.封装分页信息
        PageInfo<ContentListBO> pageInfo = new PageInfo<>(contentBoList);
        pageInfo.setTotal(p.getTotal());
        pageInfo.setPages(p.getPages());
        return pageInfo;
    }

    @Override
    public ContentBO selectContentById(Integer contentId) {
        Content content = contentDao.selectById(contentId);
        ContentBO contentBO = contentConverter.poToBo(content);
        return contentBO;
    }

    @Override
    public Integer countContentById(Integer contentId) {
        return contentDao.countContentById(contentId);
    }
}
